//
// Created by LiuYou on 2021/8/12.
//



#include <cassert>
#include <netdb.h>
#include <cstdio>
#include <unistd.h>


int main(int argc, char** argv) {
    assert( argc == 2 );
    char* host = argv[1];
    // 获取目标主机地址信息
    hostent* ptrHostInfo = gethostbyname( host );
    assert( ptrHostInfo );
    // 获取daytime服务信息
    servent* ptrServerInfo = getservbyname( "daytime", "tcp" );
    assert( ptrHostInfo );
    fprintf( stdout, "daytime port is %d\n", ntohs( ptrServerInfo->s_port ));

    sockaddr_in remoteAddress = {
            .sin_family=AF_INET,
    };
    remoteAddress.sin_port = ptrServerInfo->s_port;
    remoteAddress.sin_addr = *(in_addr*) *ptrHostInfo->h_addr_list;

    int socketFd = socket( AF_INET, SOCK_STREAM, 0 );
    int ret = connect( socketFd, (sockaddr*) &remoteAddress, sizeof( remoteAddress ));
    assert( ret != -1 );

    char buffer[128];
    ret = read( socketFd, buffer, sizeof( buffer ));
    assert( ret > 0 );
    buffer[ret] = '\0';
    fprintf( stdout, "the day time is: %s", buffer );


    close( socketFd );
    return 0;
}